﻿using Manager.Model;
using Manager.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Manager.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ArticleController : ControllerBase
    {
        private readonly ArticleService articleService;

        public ArticleController(ArticleService articleService)
        {
            this.articleService = articleService;
        }

        [HttpPost("Add")]
        public ObjectResult AddArticle([FromBody] Article article)
        {
            article.ArticleStatus = "publish";
            article.ArticlePubDate = DateTime.Now.ToString("yyy-MM-dd HH:mm:ss");
            articleService.AddArticle(article);
            return new ObjectResult(new { success = true });
        }

        [HttpGet("list")]
        public ObjectResult GetArticles(int pageNum, int pageSize)
        {
            var articles = articleService
                .GetArticles()
                .Take(pageSize)
                .Skip((pageNum - 1) * pageSize)
                .ToList();
            var count = articleService.GetArticles().Count();
            return new ObjectResult(
                new
                {
                    success = true,
                    data = articles,
                    total = count
                }
            );
        }

        [HttpPut("update")]
        public ObjectResult UpdateArticle([FromBody] Article article)
        {
            articleService.UpdateArticle(article);
            return new ObjectResult(new { success = true });
        }

        [HttpDelete("delete")]
        public ObjectResult DeleteArticle(int id)
        {
            articleService.DeleteArticle(id);
            return new ObjectResult(new { success = true });
        }

        [HttpGet("getById")]
        public ObjectResult GetArticleById(int id)
        {
            var article = articleService.GetArticleById(id);
            return new ObjectResult(new { success = true, data = article });
        }
    }
}
